package com.xieman.anti.replay.utils;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Objects;

public class DateTimeUtils {

    private static final String DEFAULT_DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";

    /**
     * @description 离现在多少秒
     * @author XQF.Sui
     * @date 2021/7/22 22:29
     * @param timestamp
     * @reutrn long
     */
    public static long betweenNowSeconds(Long timestamp) {
        return betweenNowSeconds(
                LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()));
    }

    public static long betweenNowSeconds(LocalDateTime time) {
        return ChronoUnit.SECONDS.between(time, LocalDateTime.now());
    }

    public static long betweenNowSeconds(Date date) {
        return ChronoUnit.SECONDS.between(dateToDateTime(date), LocalDateTime.now());
    }

    public static long afterNowSeconds(Date date) {
        return ChronoUnit.SECONDS.between(LocalDateTime.now(), dateToDateTime(date));
    }

    public static Date getNow() {
        return Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    }

    public static String getNowString() {
        return format(getNow());
    }

    public static String format(Date date) {
        return format(date, DEFAULT_DATE_TIME_FORMATTER);
    }

    public static String format(Date date, String pattern) {
        return Objects.isNull(date)
                ? null
                : DateTimeFormatter.ofPattern(
                        StringUtils.defaultString(pattern, DEFAULT_DATE_TIME_FORMATTER))
                .format(dateToDateTime(date));
    }

    public static LocalDateTime dateToDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
}
